﻿using CJAtech.BBS.DataEntity;
using CJAtech.BBS.Process;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bigger.Framework;
using Bigger.Web.Helper;

namespace CJAtech.BBS.Process
{
    public class SSOProcess
    {
        public CommunityConfig CommunityConfig { get; set; }

        public SSOProcess(CommunityConfig objCommunityConfig)
        {
            if (objCommunityConfig == null)
            {
                throw new Exception("对不起，社区配置不能为空");
            }
            this.CommunityConfig = objCommunityConfig;
        }

        public void LoginOut(string token)
        {
            (this.CommunityConfig.SSODomain + "/Authorize/ClearToken").CreateHttpGet(new { projectCode = this.CommunityConfig.SSOProjectCode, token = token });
        }

        public bool CheckLogin(string token)
        {
            return string.Format(this.CommunityConfig.SSODomain + "/Authorize/TokenGetCredence?projectCode={0}&token={1}", this.CommunityConfig.SSOProjectCode, token).CreateHttpGet() != "no";
        }

        [Obsolete("兼容旧版SSO，新版请使用CreateRedirectConvertUrl代替")]
        public string CreateRedirectUrl(string requestUrl, string urlFormat = "")
        {
            CJClient objCJClient = new CJClient();
            string domain = SystemWebAsset.GetDomain();
            string targetUrl = null;
            if (urlFormat.IsNull())
            {
                targetUrl = string.Format("{0}/{1}/{2}/{3}?targetUrl={4}", domain, this.CommunityConfig.TargetController, this.CommunityConfig.ConfigCode, this.CommunityConfig.TargetAction, requestUrl.EncodeUrl());
            }
            else
            {
                //{Domain}/{TargetController}/{ConfigCode}/{TargetAction}?targetUrl={TargetUrl}
                targetUrl = urlFormat.Replace("{Domain}", domain)
                    .Replace("{TargetController}", this.CommunityConfig.TargetController)
                    .Replace("{ConfigCode}", this.CommunityConfig.ConfigCode)
                    .Replace("{TargetAction}", this.CommunityConfig.TargetAction)
                    .Replace("{TargetUrl}", requestUrl.EncodeUrl());
            }
            return objCJClient.BuildAuthUrl(this.CommunityConfig.SSODomain + "/Authorize/Index", "", this.CommunityConfig.SSOSecret, targetUrl, new Dictionary<string, string> { { "auth_type", this.CommunityConfig.SSOAuthType }, { "projectCode", this.CommunityConfig.SSOProjectCode } }, DateTime.Now);
        }

        public string CreateRedirectConvertUrl(string requestUrl, string urlFormat = "")
        {
            CJClient objCJClient = new CJClient();
            string domain = SystemWebAsset.GetDomain();
            string targetUrl = null;
            if (urlFormat.IsNull())
            {
                targetUrl = string.Format("{0}/{1}/{2}?targetUrl={3}", domain, this.CommunityConfig.TargetController, this.CommunityConfig.TargetAction, requestUrl.EncodeUrl());
            }
            else
            {
                //{Domain}/{TargetController}/{TargetAction}?targetUrl={TargetUrl}
                targetUrl = urlFormat.Replace("{Domain}", domain)
                    .Replace("{TargetController}", this.CommunityConfig.TargetController)
                    .Replace("{TargetAction}", this.CommunityConfig.TargetAction)
                    .Replace("{TargetUrl}", requestUrl.EncodeUrl());
            }
            return objCJClient.BuildAuthUrl(this.CommunityConfig.SSODomain + "/Authorize/Index", "", this.CommunityConfig.SSOSecret, targetUrl, new Dictionary<string, string> { { "auth_type", this.CommunityConfig.SSOAuthType }, { "projectCode", this.CommunityConfig.SSOProjectCode } }, DateTime.Now);
        }

        [Obsolete("奔驰用户接口的SSO用户格式，新版SSO使用GetUserInfoConvert")]
        public UserInfo GetUserInfo(string token)
        {
            CacheLoginModel objCacheLoginModel = string.Format(this.CommunityConfig.SSODomain + "/Authorize/TokenGetCredence?projectCode={0}&token={1}", this.CommunityConfig.SSOProjectCode, token).CreateHttpGet<CacheLoginModel>();
            UserInfo objUserInfo = null;
            if (!objCacheLoginModel.IsLogin || objCacheLoginModel.Info == null)
            {
                return objUserInfo;
            }
            return objUserInfo = new UserInfo
            {
                UserId = objCacheLoginModel.Info.Id,
                UserName = objCacheLoginModel.Info.Field1,
                Avatar = objCacheLoginModel.Info.Avatar
            };
        }

        public UserInfo GetUserInfoConvert(string token)
        {
            string str = string.Format(this.CommunityConfig.SSODomain + "/Authorize/TokenGetCredence?projectCode={0}&token={1}", this.CommunityConfig.SSOProjectCode, token).CreateHttpGet();
            YxResult objYxResult = string.Format(this.CommunityConfig.SSODomain + "/Authorize/TokenGetCredence?projectCode={0}&token={1}", this.CommunityConfig.SSOProjectCode, token).CreateHttpGet<YxResult>();
            UserInfo objUserInfo = null;
            if (objYxResult == null || objYxResult.Code != 1000)
            {
                return objUserInfo;
            }
            var objDictionary = objYxResult.Data as Dictionary<string, object>;
            object obj = null;
            objUserInfo = new UserInfo();
            if (objDictionary.TryGetValue("UserId", out obj))
            {
                objUserInfo.UserId = obj != null ? obj.ToString() : "";
            }
            if (objDictionary.TryGetValue("UserName", out obj))
            {
                objUserInfo.UserName = obj != null ? obj.ToString() : "";
            }
            if (objDictionary.TryGetValue("Avatar", out obj))
            {
                objUserInfo.Avatar = obj != null ? obj.ToString() : "";
            }
            return objUserInfo;
        }

        public bool ValidTicket()
        {
            return CJUtils.VerifyResponse(HttpContext.Current.Request.Url.AbsoluteUri, this.CommunityConfig.SSOSecret);
        }
    }
}